package org.web.datajpa.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import org.web.datajpa.constant.ResultEnum;
import org.web.datajpa.domain.Teacher;
import org.web.datajpa.exception.ResultException;
import org.web.datajpa.service.TeacherService;
import org.web.datajpa.util.PageResultUtil;
import org.web.datajpa.util.ResultUtil;
import org.web.datajpa.vo.PageQueryVo;
import org.web.datajpa.vo.PageResult;
import org.web.datajpa.vo.Result;
import org.web.datajpa.vo.SortParam;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/api/teacher")
public class TeacherApiController {
    @Autowired
    private TeacherService teacherService;

    // ①没有用Result
    // 获取所有教师信息
    @GetMapping("/listPro")
    public List<Teacher> findAllPro(){ return teacherService.findAll();
    }
    // 添加学生
    @PostMapping("/addPro")
    public Teacher addPro(Teacher teacher){
        return teacherService.add(teacher);
    }
    // 更新学生信息
    @PutMapping("/updatePro")
    public Teacher updatePro(Teacher teacher){
        return teacherService.update(teacher);
    }
    // 删除学生信息
    @DeleteMapping("/deletePro/{id}")
    public void deleteByIdPro(@PathVariable Long id){
        teacherService.deleteById(id);
    }
    // 根据id查找学生信息
    @GetMapping("Pro/{id}")
    public Teacher findByIdPro(@PathVariable Long id){
        return teacherService.findById(id);
    }
    // 根据姓名查找学生信息
    @GetMapping("/searchPro")
    public List<Teacher> searchStudentsPro(@RequestParam String name) {
        return teacherService.searchByName(name);
    }


    // ②利用ResultUtil和Result改造crud
    // 获取所有教师信息
    @GetMapping("/list")
    public Result<List<Teacher>> findAll(){ return ResultUtil.success(teacherService.findAll());
    }
    // 添加学生
    @PostMapping("/add")
    public Result<Teacher> add(Teacher teacher){
        return ResultUtil.success(teacherService.add(teacher));
    }
    // 更新学生信息
    @PutMapping("/update")
    public Result<Teacher> update(Teacher teacher){
        return ResultUtil.success(teacherService.update(teacher));
    }
    // 删除学生信息
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Long id){
        teacherService.deleteById(id);
        return ResultUtil.success("删除成功!");
    }
    // 根据id查找学生信息
    @GetMapping("/{id}")
    public Result<Teacher> findById(@PathVariable Long id){
        return ResultUtil.success(teacherService.findById(id));
    }
    // 根据姓名查找学生信息
    @GetMapping("/search")
    public Result<List<Teacher>> searchStudents(@RequestParam String name) {
        return ResultUtil.success(teacherService.searchByName(name));
    }

    // 登录校验
    @GetMapping("/validate")
    public Result validateSnoAndPsw(Long id, String password) throws Exception {
        teacherService.validateIdAndPwd(id, password);
        return ResultUtil.success("用户"+id+"登录成功！");
        //return ResultUtil.success(studentService.validateIdAndPwd(id, password));
    }

    // 批量删除学生信息
    @DeleteMapping("/deletes/{ids}")
    public Result deleteTeacherByIds(@PathVariable String ids) {
        try {
            // 将路径中的逗号分隔字符串解析成 List<Integer>
            List<Integer> idList = Stream.of(ids.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            teacherService.deleteTeachersByIds(idList);
            return ResultUtil.success("批量删除成功");
        } catch (IllegalArgumentException e) {
            return ResultUtil.error("删除失败：" + e.getMessage());
        } catch (Exception e) {
            return ResultUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 分页查询学生信息,可以实现按照表头排序
    @PostMapping("/page")
    public PageResult getAllStuByPageWithSort(@RequestBody PageQueryVo<Teacher> pageQueryVo) {
        // 默认分页参数
        Integer pageIndex = 0;
        Integer pageSize = 10;

        if (pageQueryVo == null) {
            // pageQueryVO为空直接走默认分页查询
            Pageable pageable = PageRequest.of(pageIndex, pageSize);
            Page<Teacher> teachers = teacherService.getAll(pageable);
            return PageResultUtil.success(teachers.getContent(), teachers.getTotalElements());
        } else {
            pageIndex = pageQueryVo.getPage() > 0 ? pageQueryVo.getPage() - 1 : 0;
            pageSize = pageQueryVo.getLimit();

            Sort sort = Sort.unsorted();
            if (pageQueryVo.getSorts() != null && !pageQueryVo.getSorts().isEmpty()) {
                // 构建Sort对象，根据前端传入的多个排序参数
                sort = buildSort(pageQueryVo.getSorts());
            }else {
                // 如果没有排序规则，则默认按照id升序排序
                sort = Sort.by(Sort.Direction.ASC, "teacherId");
            }

            Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);

            if (pageQueryVo.getData() instanceof Teacher) {
                Teacher teacher = pageQueryVo.getData();
                ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                        .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                        .withIgnoreNullValues();

                Example<Teacher> example = Example.of(teacher, exampleMatcher);

                Page<Teacher> teacherPage = teacherService.getAll(example, pageable);
                return PageResultUtil.success(teacherPage.getContent(), teacherPage.getTotalElements());
            } else {
                throw new ResultException(ResultEnum.QUERY_ERROR);
            }
        }
    }

    // 根据前端传入的多个排序参数构建Sort对象
    // sorts 前端传入的多个排序参数，
    //格式如：[{"field":"id","type":"ASC"},{"field":"age","type":"DESC"}]
    private Sort buildSort(List<SortParam> sorts) {
        List<Sort.Order> orders = new ArrayList<>();
        for (SortParam param : sorts) {
            Sort.Direction direction = param.getType()
                    .equalsIgnoreCase("ASC") ? Sort.Direction.ASC : Sort.Direction.DESC;
            orders.add(new Sort.Order(direction, param.getField()));
        }
        return Sort.by(orders);
    }

    // 普通分页查询学生信息
    @PostMapping("/getByPage")
    public PageResult getAllStuByPage(@RequestBody PageQueryVo<Teacher> pageQueryVo) {
        //按id排序
        Sort sort = Sort.by(Sort.Direction.ASC, "teacherId");
        Integer pageIndex = 0;
        Integer pageSize = 10;

        if (pageQueryVo == null) {
            //pageQueryVO为空直接走默认分页查询
            Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
            Page<Teacher> teachers = teacherService.getAll(pageable);
            return PageResultUtil.success(teachers.getContent(), teachers.getTotalElements());
        } else {
            pageIndex = pageQueryVo.getPage() > 0 ? pageQueryVo.getPage() - 1 : 0;
            pageSize = pageQueryVo.getLimit();

            if (pageQueryVo.getData() instanceof Teacher) {
                Teacher teacher = pageQueryVo.getData();
                Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);

                ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                        .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                        .withIgnoreNullValues();

                Example<Teacher> example = Example.of(teacher, exampleMatcher);

                Page<Teacher> studentPage = teacherService.getAll(example, pageable);
                return PageResultUtil.success(studentPage.getContent(), studentPage.getTotalElements());
            } else {
                throw new ResultException(ResultEnum.QUERY_ERROR);
            }
        }
    }
}
